﻿<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>ajax</title>
		<style>
			*{
				margin:0;
				padding:0;
			}
			ul,li{
				list-style:none;
			}
			#list{
				width:500px;
				height:300px;
				margin:300px auto;
				position:relative;
			}
			#txt{
				width:300px;
				height:50px;
			}
			ul{
				position:absolute;
				top:50px;
				left:0;
				display:none;
				border:1px solid #ccc;
				width:300px;
			}
			.active{
				background:blue;
				cursor:pointer;
			}
		</style>
	</head>
	<body>
		<div id="list">
			<input id="txt" type="text"></input>
			<button>点击搜索</button>
			<ul id="listul">
			
			</ul>
		</div>
		
	</body>
	<script type="text/javascript">
		var txt=document.getElementById("txt");
		var oUl=document.getElementById("listul");
		var content="";
		var j=-1;
		var lilist=[];
		//当键被按下
		txt.onkeypress=function(){
			content=txt.value;
			//jsonp
			jsonp();
		}
		//jsonp
		function jsonp(){
			var _script=document.createElement("script");
			_script.src="http://suggestion.baidu.com/su?wd=" + content +" &cb=result";
			document.body.appendChild(_script);
		}
		//设置回调函数,处理返回的数据
		function result(data){
			var arr=[];
			arr=JSON.parse(JSON.stringify(data.s));
			oUl.innerHTML="";
			for(var i=0;i<arr.length;i++){
				var li=document.createElement("li");
				li.innerHTML=arr[i];
				oUl.appendChild(li);
				oUl.style.display="block";
			}
			lilist=oUl.children;
			//给li 加点击事件
			for(var m=0;m<lilist.length;m++){
				lilist[m].onclick=function(){
					txt.value=this.innerHTML;
					oUl.style.display="none";
				}
				lilist[m].onmouseover=function(){
					for(var i=0;i<lilist.length;i++){
						lilist[i].className="";
					}
					this.className="active";
				}
			}
		}
		
		document.onkeyup=function(e){
			var e=e || event;
			for(var i=0;i<lilist.length;i++){
				lilist[i].className="";
			}
			//下键
			if(e.keyCode==40){
				j++;
				j>=lilist.length?j=0:j;
				lilist[j].className="active";
			}
			//上键
			if(e.keyCode==38){
				j--;
				j<0?j=lilist.length-1:j;
				lilist[j].className="active";
			}
			if(e.keyCode==13){
				txt.value=lilist[j].innerHTML;
				oUl.style.display="none";
			}
		}
	</script>
</html>











